const queryString = require("querystring");
const goodsRouterHandler = require("./router/goods");
const userRouterHandler = require("./router/user");
const {
  GOODS_LIST,
  GOODS_DETAIL,
  GOODS_EDIT,
  GOODS_NEW,
  USER_LIST,
  USER_LOGIN,
  USER_REFISTER,
  USER_INFO,
} = require("./router/routerConst");
const existPaths = [
  GOODS_LIST,
  GOODS_DETAIL,
  GOODS_EDIT,
  GOODS_NEW,
  USER_LIST,
  USER_LOGIN,
  USER_REFISTER,
  USER_INFO,
];
const initParams = (req) => {
  req.method = req.method.toLowerCase();
  req.path = req.url.includes("?") ? req.url.split("?")[0] : req.url;
  return new Promise((resolve, reject) => {
    // 处理请求参数，分get和post
    if (req.method === "get") {
      let params = req.url.includes("?") ? req.url.split("?")[1] : "";
      req.query = queryString.parse(params);
      req.reqdata = req.query;
      resolve();
    } else if (req.method === "post") {
      let params = "";
      req.on("data", (chunk) => {
        params += chunk;
      });
      req.on("end", () => {
        req.body = queryString.parse(params);
        req.reqdata = req.body;
        resolve();
      });
    }
  });
};
console.log("process.env.NODE_ENV", process.env.NODE_ENV);

const serverHandler = async (req, res) => {
  req.path = req.url.includes("?") ? req.url.split("?")[0] : req.url;
  if (existPaths.includes(req.path)) {
    res.writeHead(200, {
      "Content-Type": "application/json; charset=utf-8",
    });
    initParams(req).then(async () => {
      let goodsData = await goodsRouterHandler(req, res);
      if (goodsData) {
        res.end(JSON.stringify(goodsData));
        return;
      }
      let userData = await userRouterHandler(req, res);
      if (userData) {
        res.end(JSON.stringify(userData));
        return;
      }
    });
  } else {
    res.writeHead(404, {
      "Content-Type": "text/plain; charset=utf-8",
    });
    res.end("404 Not Found!");
  }

  // if (req.method == "get") {
  //   res.end(JSON.stringify(req.query))
  // } else if (req.method == "post") {
  //   res.end(req.body)
  // }
};
module.exports = serverHandler;
